package com.million.base;


import com.million.base.annotations.Eviction;
import com.million.service.EvictionStrategy;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author miki
 * @Date 2022/1/22 1:38
 * @Explain 基于注解的淘汰策略工厂
 */
@Component
public class EvictionStrategyAnnotationParseFactory implements ApplicationContextAware {

    private ApplicationContext applicationContext;

    private final Map<String, EvictionStrategy> evictionStrategyMap = new HashMap<>(8);

    public EvictionStrategy getEviction(String inputEviction) {
        Map<String, EvictionStrategy> evictionStrategyMap = evictionStrategyMap();
        EvictionStrategy evictionStrategy = evictionStrategyMap.get(inputEviction);
        if (evictionStrategy == null) {
            throw new UnsupportedOperationException(String.format("input eviction is %s ,not support", inputEviction));
        }
        return evictionStrategy;
    }

    /**
     * 组装evictionMap
     *
     * @return
     */
    private Map<String, EvictionStrategy> evictionStrategyMap() {

        if (CollectionUtils.isEmpty(evictionStrategyMap)) {
            Map<String, Object> evictionBeanMap = applicationContext.getBeansWithAnnotation(Eviction.class);
            for (Object bean : evictionBeanMap.values()) {
                if (bean instanceof EvictionStrategy) {
                    String evictionAnnotationValue = bean.getClass().getAnnotation(Eviction.class).value();
                    evictionStrategyMap.put(evictionAnnotationValue, (EvictionStrategy) bean);
                }
            }
        }
        return evictionStrategyMap;
    }


    @Override
    public void setApplicationContext(ApplicationContext context) throws BeansException {
        applicationContext = context;
    }
}
